package com.cxb;

import android.app.*;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.*;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.ResolveInfo;
import android.content.res.Configuration;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.drawable.AnimationDrawable;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.*;
import android.os.Handler.Callback;
import android.speech.RecognizerIntent;
import android.speech.tts.TextToSpeech;
import android.telephony.*;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.WindowManager;
import android.widget.*;
import android.widget.CompoundButton.OnCheckedChangeListener;
import com.amitek.aidl.mqtt.bean.BindStatus;
import com.amitek.aidl.mqtt.bean.StatInfo;
import com.cxb.entity.*;
import com.cxb.manager.*;
import com.cxb.manager.WifiApManager.OnWifiApStateChangedListener;
import com.cxb.service.CXBMainService;
import com.cxb.service.CameraDayNightService;
import com.cxb.service.FloatService;
import com.cxb.service.MemoryCleanUpService;
import com.cxb.utils.*;
import com.cxb.utils.Debug;
import com.cxb.utils.Tts.TtsState;
import com.cxb.utils.Tts.TtsStateListener;
import com.cxb.view.*;
import de.greenrobot.event.EventBus;
import org.xutils.x;

import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.*;

//import com.cxb.manager.WeatherManager;

public class MainActivity extends BaseActivity implements Callback,
        TtsStateListener, OnWifiApStateChangedListener {
    private TextView tvOperationName, tvDayTime, tvNetType;
    private int digitalImages[] = {R.drawable.dig_0, R.drawable.dig_1,
            R.drawable.dig_2, R.drawable.dig_3, R.drawable.dig_4,
            R.drawable.dig_5, R.drawable.dig_6, R.drawable.dig_7,
            R.drawable.dig_8, R.drawable.dig_9};
    private ImageView ivSignalStrength, iv_wifi_ap, iv_wifi_status, iv_wifi,
            iv_wifi_ap_status;
    private View btnNavigation, btnRecord, ll_fm_tran, ivMsg, ll_wifi,
            ll_wifi_ap, ivSetting;
    private View llVolumn;
    private View btnSetting, btnHistory, btnCharger, weixin_bind, btn_shuipai,
            btn_shuilu;
    private ImageView ivAudio;
    private Context context;
    private PhoneSignalStateListener phoneSignalStateListener;
    private TelephonyManager telephoneyManager = null;
    private SharedPreferencesUtils sp = null;
    public String szLog = null;
    private Handler mHandler = null;
    // private WeatherManager weatherManager = null;
    // private WeatherView weatherView = null;
    public final static int MSG_TYPE_UPDATE_WEATHERICON = 2;
    public final static int MSG_TYPE_REFRESH_CAR_RECORDER_STATE = 3;
    public final static int MSG_TYPE_WEATHER_LOADING_STATUE = 6;
    public final static int MSG_TYPE_REFRESH_DAY_TIME = 101;
    public final static int MSG_MOVE_MAP_BACKGROUND = 102;
    public final static int MSG_SHOW_COMPASS = 103;
    private WifiManager wifiManager;
    private WifiAPUtil wifiAPUtil;
    private SMSManager smsManager;
    public static Tts tts = null;
    public static boolean need2sendCheatMsg = true;
    public static String analysisResult = null;
    private final static String ACTION_CHEAT_MESSAGE_RESULT = "action.cxb.cheat.send.result";
    // private WeatherManager weatherManager;
    private NavigationManager navigationManager;
    private PhoneManager phoneManager;
    private PowerManager powerManager;
    private ImageView ivRecording;
    private WifiApManager wifiApManager;
    private BroadcastReceiver broadcastReceiver;
    private static boolean firstBootComplete = true;
    private static boolean firstSettingMap = true;
    private static boolean has_check_cheat_state = false;
    private boolean wifiState = false;
    private AlertDialog wifiSettingDialog;
    public static boolean update_find = false;
    public boolean needWifiTip = false;
    private long lastWeatherPlay = 0;
    private ProgressDialog setUpMapDialog;
    private AudioManager audioManager;
    private WindowManager windowManager;
    private ScreenCoverDialog screenCoverDialog;
    private static boolean setUp_map = true;
    private CompassView3 compassView;
    private boolean isMapRuning = false;
    private Switch3GStateTask switch3gStateTask;
    private boolean isCheck3G = false;
    ;
    private static boolean isReset3GData = true;
    private boolean isSetupInit = false;
    private static int checkIMEICountDown = 4;

    private Button btn_closeAutoNavi;
    private final static String TAG = "MainActivity";

    //主界面背景
//    private RelativeLayout rl_main;
    //监听语音广播
    private static final String VOICEBROADCASE = "android.speech.action.VOICE_SEARCH_RESULTS";
//	private VoiceBrocast voiceBrocast;

    protected void onCreate(Bundle savedInstanceState) {
        // getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        super.onCreate(savedInstanceState);


        //
        // Intent intent=new Intent();
        // intent.setClass(this, TTSTest.class);
        // // intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        // startActivity(intent);
        // startService(new Intent(this, ScreenMonitor.class));

        switch3gStateTask = new Switch3GStateTask();
        try {

            Intent checkIntent = new Intent();
            checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
            startActivityForResult(checkIntent, 1);
        } catch (Exception e) {
            e.printStackTrace();
        }
        ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
        screenCoverDialog = new ScreenCoverDialog(getApplicationContext());
        // powerManager=(PowerManager) getSystemService(Context.POWER_SERVICE);
        // WakeLock
        // wakeLock=powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK,
        // "cxb");
        // wakeLock.acquire();
        if (manager != null
                && NetworkManager.getMobileDataEnabled(manager) == false)
            NetworkManager.setMobileDataEnabled(manager, true);
        wifiAPUtil = new WifiAPUtil();
        sp = new SharedPreferencesUtils(MainActivity.this);
        initApplication();
        setContentView(R.layout.activity_main);


//        rl_main=(RelativeLayout) findViewById(R.id.main_bg);
//        rl_main.getBackground().setAlpha(120);
        wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);

        context = getApplicationContext();
        phoneManager = new PhoneManager(this);

        Debug.printf("test", "main oncreate===");

        mHandler = new Handler(this);
        // weatherManager = new WeatherManager(this);
        // weatherManager.registerUpdateWeatherCallBack(this);
        audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        // tts = new Tts(getApplicationContext());
        // tts.registerTtsStateChange(this);

        mHandler.sendEmptyMessageDelayed(MSG_SHOW_COMPASS, 20000);
        smsManager = new SMSManager(this);

        //
        // // 启动导航监听
        navigationManager = new NavigationManager(this);
        navigationManager.startupNavigationListener();
        CxbEventBus.resgist(CxbEventBus.EVENT_WEATHER_UPDATE, this);
        CxbEventBus.resgist(CxbEventBus.EVENT_MESSAGE_CHANGE, this);
        CxbEventBus.resgist(CxbEventBus.EVENT_GPS_CHANGE, this);
        EventBus.getDefault().register(this);
        startService(new Intent(this, CXBMainService.class));
        startService(new Intent(this, CameraDayNightService.class));
        // startService(new Intent(this, WeatherMonitorService.class));
        // startService(new Intent(this, CheckUpdateService.class));
        startService(new Intent(this, MemoryCleanUpService.class));

        x.task().postDelayed(new Runnable() {

            @Override
            public void run() {
                Intent recorderIntent = new Intent();
                recorderIntent.setClassName("com.cxb.carrecorder",
                        "com.cxb.carrecorder.PreviewService");
                startService(recorderIntent);// 启动行车记录仪服务

            }
        }, 3000);
        // 启动行车记录仪服务MainActivity
        // PushService.actionStart(getApplicationContext());
        // PushService2.actionStart(getApplicationContext());

        //
        // new PhoneManager(this).setCallState(PhoneState.ACTIVE);
        // PhoneDialogView.getInstance(this).show();
        wifiState = wifiManager.isWifiEnabled();
        // setGprsEnabled(true);
        ivRecording = (ImageView) findViewById(R.id.iv_recording);
        //11111111111
        iv_wifi = (ImageView) findViewById(R.id.iv_wifi);
        iv_wifi_ap_status = (ImageView) findViewById(R.id.iv_wifi_ap_status);

        compassView = (CompassView3) findViewById(R.id.ib_compass);
        btn_shuipai = findViewById(R.id.btn_shuipai);
        btn_shuilu = findViewById(R.id.btn_shuilu);
        btn_shuilu.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (CommonUtils.isWeixinBind()) {
                    Intent intent = new Intent();
                    intent.setClassName("com.cxb.carrecorder",
                            "com.cxb.carrecorder.PreviewService");
                    intent.setAction("ACTION_GET_VIDEO_SHARE");
                    startService(intent);
                } else {
                    Tts.showToast(getApplication(),
                            getString(R.string.share_fail_because_unbind), 0);
                    Intent intent = new Intent();
                    intent.setClass(MainActivity.this, WeiXinBindActivity.class);
                    startActivity(intent);
                }
            }
        });
        btn_shuipai.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (CommonUtils.isWeixinBind()) {
                    Intent intent = new Intent();
                    intent.setClassName("com.cxb.carrecorder",
                            "com.cxb.carrecorder.PreviewService");
                    intent.setAction("ACTION_GET_PICTURE_SHARE");
                    startService(intent);
                } else {
                    Tts.showToast(getApplication(),
                            getString(R.string.share_fail_because_unbind), 0);
                    Intent intent = new Intent();
                    intent.setClass(MainActivity.this, WeiXinBindActivity.class);
                    startActivity(intent);
                }

            }
        });

        btn_closeAutoNavi = (Button) findViewById(R.id.btn_closeAutoNavi);

        wifiApManager = new WifiApManager(this);
        wifiApManager.registerWifiApStateChangedListener(this);
        if (sp.getWifiApEnable()) {
            wifiApManager.changeWifiApState(true);
        }

        Log.e(TAG, "ADDRESS: oncreate");
        broadcastReceiver = new MainBroadCastReceiver();
        IntentFilter intentFilter = new IntentFilter(
                Constants.ACTION_FM_TX_SWITCH);
        intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        intentFilter.addAction(ACTION_CHEAT_MESSAGE_RESULT);
        intentFilter.addAction(Constants.ACTION_UPDATE_FIND);
        intentFilter.addAction("com.cxb.weatherUpdate");
        intentFilter.addAction("android.media.VOLUME_CHANGED_ACTION");
        this.registerReceiver(broadcastReceiver, intentFilter);

        TextView wifiTip = new TextView(this);
        wifiTip.setTextSize(16);
        wifiTip.setTextColor(Color.WHITE);
        wifiTip.setText(R.string.wifi_open_tip);
        LinearLayout ll = new LinearLayout(this);
        LinearLayout.LayoutParams layout = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        ll.setGravity(Gravity.CENTER);
        ll.setOrientation(LinearLayout.VERTICAL);
        ll.setLayoutParams(layout);

        CheckBox checkBox = new CheckBox(this);
        checkBox.setText(R.string.no_longer_remind);
        ll.addView(wifiTip);
        ll.addView(checkBox);
        wifiSettingDialog = new AlertDialog.Builder(this)
                .setView(ll)
                .setPositiveButton(getString(R.string.setting),
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                Intent intent = new Intent();
                                intent.setClass(MainActivity.this,
                                        WifiActivity.class);
                                startActivity(intent);
                                dialog.dismiss();
                            }

                        })
                .setNegativeButton(getString(R.string.cancel),
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                dialog.dismiss();
                            }

                        }).setTitle(R.string.prompt).create();

        // wifiSettingDialog.setTitle(R.string.prompt);
        // wifiSettingDialog.setMessage(getString(R.string.wifi_open_tip));

        // TextView wifiTip = new TextView(this);
        // wifiTip.setText(R.string.wifi_open_tip);
        // LinearLayout ll = new LinearLayout(this);
        // LinearLayout.LayoutParams layout = new LinearLayout.LayoutParams(
        // LinearLayout.LayoutParams.WRAP_CONTENT,
        // LinearLayout.LayoutParams.WRAP_CONTENT);
        // ll.setGravity(Gravity.CENTER);
        // ll.setOrientation(LinearLayout.VERTICAL);
        // ll.setLayoutParams(layout);
        //
        // CheckBox checkBox = new CheckBox(this);
        // checkBox.setText(R.string.no_longer_remind);
        // ll.addView(wifiTip);
        // ll.addView(checkBox);
        // wifiSettingDialog.setContentView(ll);
        checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton buttonView,
                                         boolean isChecked) {
                sp.setWifiRemain(isChecked);
            }
        });

        setUpMapDialog = new ProgressDialog(this.getApplicationContext());
        setUpMapDialog.setTitle(R.string.warn_tip);
        setUpMapDialog.setMessage(getString(R.string.setting_up_map));

        // /////////////检查行车记录仪//////////////////////////
        TimerTask timerTask = new TimerTask() {

            @Override
            public void run() {
                mHandler.sendEmptyMessage(MSG_TYPE_REFRESH_CAR_RECORDER_STATE);

            }
        };
        Timer timer = new Timer();
        timer.schedule(timerTask, 0, 1000);

        // //////////////////////////////////////////////////
        if (Config.IS_MAP_IN_SDCARD) {
            IntentFilter sdcardIntentFilter = new IntentFilter(
                    Intent.ACTION_MEDIA_MOUNTED);
            sdcardIntentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
            sdcardIntentFilter.addAction(Intent.ACTION_MEDIA_REMOVED);
            sdcardIntentFilter.addAction(Intent.ACTION_MEDIA_BAD_REMOVAL);

            sdcardIntentFilter.addDataScheme("file");
            registerReceiver(sdcardMountReceiver, sdcardIntentFilter);// 注册监听函数
        }
        // /////////////////////////////////////////////
        ivAudio = (ImageView) findViewById(R.id.iv_audio_state);
        llVolumn = findViewById(R.id.ll_audio);
        updateVolumnButton();

        llVolumn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
//				if (isMute()) {
//					setPhoneMute(false);
//				} else {
//					setPhoneMute(true);
//				}
//				updateVolumnButton();
//
//				MqttServiceProxy mqttProxy = CXBMainService.getMqttProxy();
//				if (mqttProxy != null) {
//					try {
//						mqttProxy.eventStatistics(StatInfo.VOLUMN);
//					} catch (RemoteException e) {
//						e.printStackTrace();
//					}// 行程结束
//				}
                //中英文切换  选择
               /* if(getResources().getConfiguration().locale.getDisplayLanguage().equalsIgnoreCase("English")){
                    startVoiceRecognize();
                }else {
                    if (Config.isRecognizeSupport(MainActivity.this)) {
                        Intent nIntent = new Intent();
                        ComponentName cn = new ComponentName("com.unisound.unicar.gui",
                                "com.unisound.unicar.gui.ui.GUIMainActivity");
                        nIntent.setComponent(cn);
						startActivity(nIntent);
//						sendBroadcast(new Intent("action com.unisound.unicar.gui.ui.START_WINDOWSERVICE"));
                    }
                }*/
                //启动语音
				startVoiceRecognize();
                //启动地图apk
//                startMap();

            }
        });
        // ////////////////////////////////////////////////////////////

        // Editor editor = getSharedPreferences(PushService.TAG, MODE_PRIVATE)
        // .edit();
        // editor.putString(PushService.PREF_DEVICE_ID,
        // phoneManager.getDeviceId());
        // editor.commit();
        // PushService.actionStart(getApplicationContext());
        // Editor editor = getSharedPreferences(PushService.TAG, MODE_PRIVATE)
        // .edit();
        // editor.putString(PushService.PREF_DEVICE_ID,
        // phoneManager.getDeviceId());
        // editor.commit();
        // PushService.actionStart(getApplicationContext());

        /** 2015-06-08 检查是否存在IMEI **/
        // final Timer getDeviceIdTimer = new Timer();
        // TimerTask getDeviceIdTask = new TimerTask() {
        //
        // @Override
        // public void run() {
        // TelephonyManager telephoneyManager = (TelephonyManager)
        // getSystemService(Context.TELEPHONY_SERVICE);
        // String IMEI = telephoneyManager.getDeviceId();
        // if(TextUtils.isEmpty(IMEI) && checkIMEICountDown-- > 0){
        // goDevieCannotRunningWithoutIMEI();
        // }
        // else if(!TextUtils.isEmpty(IMEI))
        // {
        // checkIMEICountDown = -1;
        // }
        // }
        // };
        //
        // getDeviceIdTimer.schedule(getDeviceIdTask, 0, 1000);
        if (sp.getIsSetupWizard()) {
            showHomeKey();
            // openYunzhisheng();
        }

        if (sp.getIsSetupWizard() && !sp.getIsSetupWizardWeiXin()) {
            // Intent goWeixinNavi = new Intent();
            // goWeixinNavi.setClass(this, SetupWizardWeixin.class);
            // this.startActivity(goWeixinNavi);
        }

        // 行程开始
        // final MqttServiceProxy mqttProxy = CXBMainService.getMqttProxy();
        // if (mqttProxy != null) {
        // try {
        // final String deviceId = telephoneyManager.getDeviceId();
        // if (deviceId == null || deviceId.length() < 15) {
        // mHandler.postDelayed(new Runnable() {
        //
        // @Override
        // public void run() {
        // try {
        // Log.i("test", "sendTrackStart imei=" + deviceId);
        // final String deviceId = telephoneyManager
        // .getDeviceId();
        // if (deviceId == null || deviceId.length() < 15) {
        // mHandler.postDelayed(this, 5000);
        // } else {
        // mqttProxy.sendTrackStart(true);
        // }
        // } catch (RemoteException e) {
        // e.printStackTrace();
        // }
        //
        // }
        // }, 5000);
        // } else {
        // mqttProxy.sendTrackStart(true);
        // }
        // } catch (RemoteException e) {
        // e.printStackTrace();
        // }// 行程结束
        // }
        // 启动翼卡app
        if (Config.isEcardSupport(this)) {
            setupECardApp();

            // 配置vpn
        }
        mHandler.postDelayed(new Runnable() {

            @Override
            public void run() {
                try {
                    ApnNode apnNode = phoneManager.getSuitableAPN();
                    if (apnNode != null) {
                        new ApnUtility(context).editApn(apnNode.getName(),
                                apnNode.getApn(), apnNode.getMcc(),
                                apnNode.getMnc());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        }, 3000);

        init();
        //判断语言 是否启用云之声
        languageStatus();

    }

    private void languageStatus() {
        String language = getResources().getConfiguration().locale.getDisplayLanguage();
        updateStatus(language);
    }

    private void updateStatus(String language) {

        if (language.equalsIgnoreCase("English")) {
            RootContext.runCommandForResult("am force-stop com.chemi.framework");
            RootContext.runCommandForResult("am force-stop com.unisound.unicar.gui");
        } else {
            RootContext.runCommandForResult("pm enable com.chemi.framework");
            RootContext.runCommandForResult("pm enable com.unisound.unicar.gui");
            RootContext
                    .runCommandForResult("am startservice -n com.unisound.unicar.gui/com.unisound.unicar.gui.ui.WindowService");
        }
    }

    /**
     * 2015-06-08 跳转到显示没有IMEI页，并关进入不可控制状态
     **/
    private void goDevieCannotRunningWithoutIMEI() {
        Intent intent = new Intent();
        intent.setClass(this, NoIMEIMessageActivity.class);
        this.startActivity(intent);
        stopHomeKey();
        this.finish();
    }

    /**
     * 获得天气
     *
     * @param json
     * @return
     */
    /*private String getWeather(String json) {
		//1111
		TextView tv_weather = (TextView) findViewById(R.id.tv_weather);
		TextView tv_value_text_pollution = (TextView) findViewById(R.id.tv_value_text_pollution);

		String str_weather = getString(R.string.noweather);
//		setPM25(null);
		*//** 如果json数据没有，表明获取异常，设置数据无效，让后台再获取 **//*
		if (json == null) {
			sp.setWeatherEffective(false);
			tv_weather.setText(str_weather);
			return str_weather;
		}
		Weather weathere = CommonUtils.getWeatherByString(json, this);
		*//** 如果数据中的白天或夜晚数据不存在，表示也有异常，设置数据无效，让后台再获取 **//*
		if (TextUtils.isEmpty(weathere.getTxt_n())
				|| TextUtils.isEmpty(weathere.getTxt_d())) {
			sp.setWeatherEffective(false);
			tv_weather.setText(str_weather);
			return str_weather;
		}
		*//** 更新UI **//*
		sp.setWeatherEffective(true);
		StringBuilder sb = new StringBuilder();
		sb.append(weathere.getCity());
		// if (!TextUtils.isEmpty(weathere.getDistrict()))
		// sb.append(weathere.getCity());
		sb.append("\t");
		Calendar calendar = new GregorianCalendar();
		if (calendar.get(Calendar.HOUR_OF_DAY) > 18) {
			sb.append(weathere.getTxt_n());
		} else {
			sb.append(weathere.getTxt_d());
		}
		sb.append("\t");
		sb.append(weathere.getTmpMin() + "℃ ~ ");
		sb.append(weathere.getTmpMax() + "℃");
		str_weather = sb.toString();
        */

    /**
     * 取消天气显示
     *//*
		tv_weather.setText(str_weather);
		tv_value_text_pollution.setText(weathere.getQlty());
//		setPM25(weathere.getPm25());

		return str_weather;
	}*/
    private void getTime() {

        mHandler.post(new Runnable() {
            @Override
            public void run()
            {
                TextView tv_weather = (TextView) findViewById(R.id.tv_weather);
                SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss ");
                Date curDate = new Date(System.currentTimeMillis());
                //获取当前时间
                String str = formatter.format(curDate);
                tv_weather.setText(str);
                mHandler.postDelayed(this, 1000);
            }
        });
    }

/*	private void setPM25(String pm25) {
		PM25View pm25_view = (PM25View) findViewById(R.id.pm25_view);
//		View digital_3 = findViewById(R.id.ll_digital_3);
//		View digital_2 = findViewById(R.id.ll_digital_2);
//		View digital_1 = findViewById(R.id.ll_digital_1);
//		View digitals[] = { digital_1, digital_2, digital_3 };

		for (int i = 0; i < digitals.length; i++)
			digitals[i].setBackgroundResource(digitalImages[0]);

		if (pm25 != null) {
			if (!TextUtils.isDigitsOnly(pm25))
				return;
			char[] pm25cs = pm25.toCharArray();
			pm25_view.setPM25Value(Integer.parseInt(pm25));
			for (int i = 0; i < digitals.length && i < pm25cs.length; i++) {
				digitals[i]
						.setBackgroundResource(digitalImages[pm25cs[pm25cs.length
								- 1 - i] - '0']);
			}
		}

	}*/

    class MainBroadCastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            //接收天气信息的广播
            if ("com.cxb.weatherUpdate".equals(intent.getAction())) {
//				getWeather(sp.getStringWeather());
            }
            if (WifiManager.WIFI_STATE_CHANGED_ACTION
                    .equals(intent.getAction())) {

                if (wifiState != wifiManager.isWifiEnabled()) {
                    wifiState = wifiManager.isWifiEnabled();
                    if (wifiState) {

                        // TTSToast.show(MainActivity.this,
                        // getString(R.string.wifi_open), 0);
                        if (!sp.getWifiRemain() && needWifiTip) {
                            wifiSettingDialog.show();
                            needWifiTip = false;
                        }
                    } else {
                        TTSToast.show(MainActivity.this,
                                getString(R.string.wifi_close), 0);
                        Log.e(TAG, "ADDRESS:" + this.toString());
                    }
                }
                updateWifiState();
            } else if (ACTION_CHEAT_MESSAGE_RESULT.equals(intent.getAction())) {
                int resultCode = getResultCode();
                if (resultCode == Activity.RESULT_OK) {
                    need2sendCheatMsg = false;
                    sp.setPictproofState(false);
                    Debug.printf("test", "cheat 防盗短信发送成功");
                } else {
                    need2sendCheatMsg = true;
                    sendCheatMessage();
                    Debug.printf("test", "cheat 防盗短信发送失败，重新发送");
                }
            } else if (WifiManager.NETWORK_STATE_CHANGED_ACTION == intent
                    .getAction()) {

                updateWifiState();
            } else if (Constants.ACTION_UPDATE_FIND == intent.getAction()) {
                ivSetting.setVisibility(View.VISIBLE);
                update_find = true;
                // updateWifiState();
            } else if (intent.getAction().equals(
                    "android.media.VOLUME_CHANGED_ACTION")) {
                Log.i("test", "VOLUME_CHANGED_ACTION");
                updateVolumnButton();
            }
        }
    }

    /**
     * 2015-06-05 发送启动Home Key的广播
     **/
    private void showHomeKey() {
        if (!isServiceRunning(this, FloatService.class.getName())) {
            this.startService(new Intent(this, FloatService.class));
        }
        //
    }

    private void showHomeKeyBroadcast() {
        Intent bcintent = new Intent(FloatService.SHOWHOMEKEY);
        this.sendBroadcast(bcintent);
    }


    private void openYunzhisheng() {
        Intent intent = new Intent();
        intent.setAction("cn.yunzhisheng.vui.assistant.ACTION.START_WAKEUP");
        intent.setAction("cn.yunzhisheng.vui.assistant.ACTION.START_WAKEUP");
        intent.putExtra("START_TALK_FROM", "START_FROM_FITST_BOOTUP");
        intent.setClassName("com.ami.voice.recognition",
                "cn.yunzhisheng.vui.assistant.WindowService");
        startService(intent);
    }

    /**
     * 2015-06-08 查找Service是否在启动中
     **/
    private boolean isServiceRunning(Context mContext, String className) {
        boolean isRunning = false;
        ActivityManager activityManager = (ActivityManager) mContext
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningServiceInfo> serviceList = activityManager
                .getRunningServices(30);
        if (!(serviceList.size() > 0)) {
            return false;
        }
        for (int i = 0; i < serviceList.size(); i++) {
            if (serviceList.get(i).service.getClassName().equals(className) == true) {
                isRunning = true;
                break;
            }
        }
        return isRunning;
    }

    /**
     * 2015-06-08 发送启动Home Key的广播
     **/
    private void stopHomeKey() {
        Intent i = new Intent();
        i.setAction(FloatService.STOPHOMEKEY);
        sendBroadcast(i);
    }


    private void setRecording(boolean isRecording) {
        if (isRecording) {
            ivRecording.setVisibility(View.VISIBLE);
            AnimationDrawable animationDrawable = (AnimationDrawable) ivRecording
                    .getDrawable();
            animationDrawable.start();
        } else {
            ivRecording.setVisibility(View.GONE);
        }
    }

    private void initApplication() {

        // 设置向导判断
        // TODO
        // !sp.getIsSetupWizard()
        if (!sp.getIsSetupWizard()) {
            Intent i = new Intent();
            i.setClass(MainActivity.this, SetupWizardActivity1.class);
            startActivity(i);
            // 拷贝百度初使设置配置
            // ////////////////////////////////////////////////////
            if (Config.getMapDefault(this) == Config.MAP_AUTONAVI) {
                writeFileToLocal("base_path.xml", "base_path.xml");
                int uid = 0;
                int gid = 0;
                try {
                    PackageManager pm = getPackageManager();
                    ApplicationInfo ai = pm.getApplicationInfo(
                            "com.autonavi.xmgd.navigator",
                            PackageManager.GET_ACTIVITIES);
                    uid = ai.uid;
                    gid = ai.uid;
                    Log.d("pumkid ", "pumkid ai.uid" + ai.uid);
                } catch (NameNotFoundException e) {
                    e.printStackTrace();
                }

                RootContext rootContext = RootContext.getInstance();

                rootContext
                        .runCommand("mkdir -p /data/data/com.autonavi.xmgd.navigator/shared_prefs");
                rootContext
                        .runCommand("cp -rf /data/data/com.cxb/files/autonavi.xml /data/data/com.autonavi.xmgd.navigator/shared_prefs/autonavi.xml");

                rootContext.runCommand("chown " + uid + ":" + gid
                        + " /data/data/com.autonavi.xmgd.navigator");
                rootContext
                        .runCommand("chown "
                                + uid
                                + ":"
                                + gid
                                + " /data/data/com.autonavi.xmgd.navigator/shared_prefs");
                rootContext
                        .runCommand("chown "
                                + uid
                                + ":"
                                + gid
                                + " /data/data/com.autonavi.xmgd.navigator/shared_prefs/autonavi.xml");
                rootContext
                        .runCommand("chmod -R 777  /data/data/com.autonavi.xmgd.navigator");
                writeFileToLocal("com.autonavi.xmgd.navigator.xml",
                        "com.autonavi.xmgd.navigator.xml");
                rootContext
                        .runCommand("cp -rf /data/data/com.cxb/files/com.autonavi.xmgd.navigator.xml /data/data/com.autonavi.xmgd.navigator/shared_prefs/com.autonavi.xmgd.navigator.xml");
                rootContext
                        .runCommand("chown "
                                + uid
                                + ":"
                                + gid
                                + " /data/data/com.autonavi.xmgd.navigator/shared_prefs/com.autonavi.xmgd.navigator.xml");
                rootContext
                        .runCommand("chmod -R 666  /data/data/com.autonavi.xmgd.navigator/shared_prefs/com.autonavi.xmgd.navigator.xml");

            } else if (Config.MAP_BAIDU == Config.getMapDefault(this)) {
                // 百度导航
                writeFileToLocal("navi.common.db.config.xml",
                        "navi.common.db.config.xml");
                writeFileToLocal("navi.xml", "navi.xml");
                int uid = 0;
                int gid = 0;
                try {
                    PackageManager pm = getPackageManager();
                    ApplicationInfo ai = pm.getApplicationInfo(
                            "com.baidu.navi", PackageManager.GET_ACTIVITIES);
                    uid = ai.uid;
                    gid = ai.uid;
                } catch (NameNotFoundException e) {
                    e.printStackTrace();
                }
                RootContext rootContext = RootContext.getInstance();

                rootContext
                        .runCommand("mkdir -p /data/data/com.baidu.navi/shared_prefs");
                rootContext
                        .runCommand("cp -rf /data/data/com.cxb/files/navi.xml /data/data/com.baidu.navi/shared_prefs/navi.xml");

                rootContext.runCommand("chown " + uid + ":" + gid
                        + " /data/data/com.baidu.navi");
                rootContext.runCommand("chown " + uid + ":" + gid
                        + " /data/data/com.baidu.navi/shared_prefs");
                rootContext.runCommand("chown " + uid + ":" + gid
                        + " /data/data/com.baidu.navi/shared_prefs/navi.xml");
                rootContext
                        .runCommand("chmod -R 777  /data/data/com.baidu.navi");
                rootContext
                        .runCommand("cp -rf /data/data/com.cxb/files/navi.common.db.config.xml /data/data/com.baidu.navi/shared_prefs/navi.common.db.config.xml");
                rootContext
                        .runCommand("chown "
                                + uid
                                + ":"
                                + gid
                                + " /data/data/com.baidu.navi/shared_prefs/navi.common.db.config.xml");
                rootContext
                        .runCommand("chmod -R 666  /data/data/com.baidu.navi/shared_prefs/navi.common.db.config.xml");

            } else if (Config.getMapDefault(this) == Config.MAP_AUTOMAP) {

                // added by huqingkui, 下面两行代码实现的效果：去掉高德导航启动欢迎界面，另外开启高德导航的
                // 保持屏幕常亮和播报实时路况
                NavigationManager.DefaultConfig defaultConfig = new NavigationManager.DefaultConfig(
                        this);
                defaultConfig.setNaviDefaultConfig();
            }

            // //////////////////////////////////////////////////
            finish();

        }
    }

    private void writeFileToLocal(final String fileName,
                                  final String targetFileName) {
        try {
            InputStream is = null;
            is = getAssets().open(fileName);
            OutputStream os = new FileOutputStream(new File(getFilesDir(),
                    targetFileName));
            int data = -1;
            while ((data = is.read()) != -1) {
                os.write(data);
            }
            os.flush();
            os.close();
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    @Override
    protected void onStart() {
        // Toast.makeText(this, getCarRecorderState()+"", 1).show();

        // if (getCarRecorderState()) {// 行車記錄儀正在錄像
        // setRecording(true);
        // } else {
        // setRecording(false);
        // }
        super.onStart();

    }

    private void init() {

        initButton();

        initPhoneState();

    }

    private void initButton() {
        // weatherView = (WeatherView) findViewById(R.id.ib_weather);
        // weatherView.updateWeatherView(null);
        // weatherView.setOnClickListener(new OnClickListener() {
        // @Override
        // public void onClick(View v) {
        // try {
        // Intent intent = new Intent();
        // intent.setClass(MainActivity.this, WeatherActivity.class);
        //
        // startActivity(intent);
        // // WeatherActivity.bRefreshLocal = true;
        // // WeatherActivity.bRefreshDest = true;
        // } catch (Exception e) {
        // e.printStackTrace();
        // }
        // }
        // });

        btnNavigation = (View) findViewById(R.id.rl_navigation);

        if (CommonUtils.getModel().equals("YX001D")) {
            btnNavigation
                    .setBackgroundResource(R.drawable.icon_navigation_yx001d);

        }
        // else if (CommonUtils.getVersionType() ==
        // CommonUtils.VERSION_ZHAOSHAN) {
        // btnNavigation
        // .setBackgroundResource(R.drawable.icon_navigation_zhaoshan);
        // }
        // btnNavigation.setBackgroundResource(ClientManager
        // .getNavigationDrawable());
        btnNavigation.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    if (CommonUtils.isSDExists(MainActivity.this)
                            || !Config.IS_MAP_IN_SDCARD) {
                        if (CommonUtils.isUSBMass()) {
                            Toast.makeText(MainActivity.this,
                                    R.string.usb_mass_cannot_use_map, Toast.LENGTH_SHORT).show();
                            Tts.speak(getString(R.string.usb_mass_cannot_use_map));
                        } else {
                            isMapRuning = true;
                            startMapViewActivity();
                        }
                    } else {
                        Toast.makeText(MainActivity.this,
                                R.string.sd_no_find_try_again, Toast.LENGTH_SHORT).show();
                        Tts.speak(getString(R.string.sd_no_find_try_again));
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        /**
         * @author pumkid 2015年7月22日13:59:35 长按关闭功能
         */
        btnNavigation.setOnLongClickListener(new OnLongClickListener() {

            @Override
            public boolean onLongClick(View v) {
                // TODO Auto-generated method stub

                if (Config.getMapDefault(MainActivity.this) == Config.MAP_BAIDU) {
                    if (checkAutoNaviPackageExisted(true, "com.baidu.navi")) {
                        closeProcess("com.baidu.navi");
                        mHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                checkAutoNaviPackageExisted(false,
                                        "com.baidu.navi");
                                tts.speak(getString(R.string.map_has_close));
                            }

                        }, 1000l);
                    }
                } else if (Config.getMapDefault(MainActivity.this) == Config.MAP_AUTOMAP) {
                    if (checkAutoNaviPackageExisted(true,
                            "com.autonavi.minimap")) {
                        closeProcess("com.autonavi.minimap");
                        mHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                checkAutoNaviPackageExisted(false,
                                        "com.autonavi.minimap");
                                tts.speak(getString(R.string.map_has_close));
                            }

                        }, 1000l);
                    }
                } else if (Config.getMapDefault(MainActivity.this) == Config.MAP_AUTONAVI) {
                    if (checkAutoNaviPackageExisted(true,
                            "com.autonavi.xmgd.navigator")) {
                        closeProcess("com.autonavi.xmgd.navigator");
                        mHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                checkAutoNaviPackageExisted(false,
                                        "com.autonavi.xmgd.navigator");
                                tts.speak(getString(R.string.map_has_close));
                            }

                        }, 1000l);
                    }
                }

                return true;
            }
        });

        btnRecord = (View) findViewById(R.id.ll_recorder);

        btnRecord.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!CommonUtils.isServiceRunning(MainActivity.this,
                        "com.cxb.carrecorder.PreviewService")) {
                    Toast.makeText(MainActivity.this, "行车记录仪启动中,请稍等...", Toast.LENGTH_SHORT)
                            .show();
                }

                Intent intent = new Intent();
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                        | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                intent.setClassName("com.cxb.carrecorder",
                        "com.cxb.carrecorder.MainActivity");
                startActivity(intent);

                try {
                    CXBMainService.getMqttProxy().eventStatistics(
                            StatInfo.RECORD);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
            }
        });

        btnCharger = (View) findViewById(R.id.ll_charge);
        btnCharger.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent i = new Intent();
                // i.setClass(MainActivity.this, ChargeActivity.class);
                i.setClass(MainActivity.this, RechangeIOPActivity.class);
                startActivity(i);

                try {
                    CXBMainService.getMqttProxy().eventStatistics(
                            StatInfo.CHARGE);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }
                // if (phoneManager.getSIMType() ==
                // PhoneManager.SIM_CAR_TYPE_IOT) {
                // Intent i = new Intent();
                // // i.setClass(MainActivity.this, ChargeActivity.class);
                // i.setClass(MainActivity.this, RechangeIOPActivity.class);
                // startActivity(i);
                // StatisticsManager
                // .onFunctionEvent(StatisticsManager.BTN_RCHARGE);
                // } else {
                // Intent i = new Intent();
                // // i.setClass(MainActivity.this, ChargeActivity.class);
                // i.setClass(MainActivity.this, RechangeActivity.class);
                // startActivity(i);
                // StatisticsManager
                // .onFunctionEvent(StatisticsManager.BTN_RCHARGE);
                // }
            }
        });

        if (Config.isEcardSupport(this)) {
            ll_wifi_ap = (View) findViewById(R.id.ll_wifi_ap);
            ll_wifi_ap.setBackgroundResource(R.drawable.icon_yicard);
            ll_wifi_ap.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent tmpIntent = new Intent("com.android.ecar.recv");
                    tmpIntent.putExtra("ecarSendKey", "StartECar");
                    MainActivity.this.sendBroadcast(tmpIntent);
                }
            });

        } else {
            ll_wifi_ap = (View) findViewById(R.id.ll_wifi_ap);
            ll_wifi_ap.setBackgroundResource(R.drawable.wifi_ap_main);
            ll_wifi_ap.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.setClass(MainActivity.this, WifiAPActivity.class);
//                    intent.setClass(MainActivity.this, SupportActivity.class);
                    startActivity(intent);
                }
            });

            // ll_wifi_ap.setOnLongClickListener(new OnLongClickListener() {
            //
            // @Override
            // public boolean onLongClick(View v) {
            // Intent intent = new Intent();
            // intent.setClass(MainActivity.this, WifiAPActivity.class);
            // startActivity(intent);
            //
            // return false;
            // }
            // });
        }
        ll_wifi = (View) findViewById(R.id.ll_wifi);
        ll_wifi.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!wifiManager.isWifiEnabled()) {
                    if (wifiApManager.isWifiApEnabled()) {
                        wifiApManager.closeWifiAp();
                    }
                }
                wifiManager.setWifiEnabled(!wifiManager.isWifiEnabled());
                needWifiTip = true;
            }
        });
        ll_wifi.setOnLongClickListener(new OnLongClickListener() {

            @Override
            public boolean onLongClick(View v) {
                Intent intent = new Intent();
                intent.setClass(MainActivity.this, WifiActivity.class);
                startActivity(intent);

                return false;
            }
        });

        iv_wifi_status = (ImageView) findViewById(R.id.iv_wifi_status);
        // iv_wifi_ap_status = (ImageView) findViewById(R.id.iv_fm_tran);
        ll_wifi_ap = (ImageView) findViewById(R.id.iv_wifi_status);

    }

    @Override
    protected void onPause() {
        super.onPause();
        if (sp.getIsSetupWizard()) {
            showHomeKeyBroadcast();
            // openYunzhisheng();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        /** 2015-06-05 onCreate里调用 **/
        if (sp.getIsSetupWizard()) {
            stopHomeKey();
            // openYunzhisheng();
        }
//		//获取当前天气信息
//		getWeather(sp.getStringWeather());
        //获取当前时间
        getTime();
        btnSetting = (View) findViewById(R.id.ib_setting);
        btnSetting.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent i = new Intent();
                i.setClass(MainActivity.this, SettingActivity.class);
                startActivity(i);

            }
        });

        updateWifiAPApState();
        updateWifiState();
        updateVolumnButton();
        if (smsManager.getSMSUnReadCount() > 0) {
            ivMsg.setVisibility(View.VISIBLE);
        } else {
            ivMsg.setVisibility(View.GONE);
        }

        if (getCarRecorderState()) {// 行車記錄儀正在錄像
            setRecording(true);
        } else {
            setRecording(false);
        }

        audioManager.setStreamMute(AudioManager.STREAM_MUSIC
                | AudioManager.STREAM_SYSTEM, false);
        if (Config.getMapDefault(this) == Config.MAP_BAIDU) {
            checkAutoNaviPackageExisted(false, "com.baidu.BaiduMap");
        } else if (Config.getMapDefault(this) == Config.MAP_AUTONAVI) {
            checkAutoNaviPackageExisted(false, "com.autonavi.minimap");
        }

    }

    private void initPhoneState() {
        tvNetType = (TextView) findViewById(R.id.tvNetType);
        tvOperationName = (TextView) findViewById(R.id.tv_operation_name);
        ivSignalStrength = (ImageView) findViewById(R.id.iv_signal_strength);
        iv_wifi_ap = (ImageView) findViewById(R.id.iv_wifi_ap);
        ivMsg = (ImageView) findViewById(R.id.ivMsg);
        ivSetting = (ImageView) findViewById(R.id.ivSetting);
        ivSetting.setVisibility(View.GONE);
        telephoneyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        Log.i(TAG, "telephoneyManager=" + telephoneyManager);
        phoneSignalStateListener = new PhoneSignalStateListener();

        telephoneyManager.listen(phoneSignalStateListener,
                PhoneStateListener.LISTEN_SERVICE_STATE
                        | PhoneStateListener.LISTEN_SIGNAL_STRENGTHS
                        | PhoneStateListener.LISTEN_CALL_STATE
                        | PhoneStateListener.LISTEN_DATA_CONNECTION_STATE);

    }

    private int noSigalCount = 0;
    private int preNetType = 0;


    private void updateSignalStrength(int strength) {
        switch (strength) {
            case 0:
                ivSignalStrength.setBackgroundResource(R.drawable.strength_0);
                break;
            case 1:
                ivSignalStrength.setBackgroundResource(R.drawable.strength_1);
                break;
            case 2:
                ivSignalStrength.setBackgroundResource(R.drawable.strength_2);
                break;
            case 3:
                ivSignalStrength.setBackgroundResource(R.drawable.strength_3);
                break;
            case 4:
                ivSignalStrength.setBackgroundResource(R.drawable.strength_4);
                break;
            case 5:
                ivSignalStrength.setBackgroundResource(R.drawable.strength_4);
                break;
            default:
                ivSignalStrength.setBackgroundResource(R.drawable.strength_0);
                break;

        }

        int networkType = PhoneSignalInfo.getNetworkType(context);
        int operatorType = PhoneSignalInfo.getMobileOperator(context);
        Debug.printf("test", " updateSignalStrength");
        if (!phoneManager.isSimCardAccess()) {
            strength = 0;
            operatorType = 0;
        }
        if (strength > 0 && isReset3GData) {
            CommonUtils.switch3GMode(MainActivity.this);
            isReset3GData = false;
        }

        EventBus.getDefault()
                .post(new EventBusMessage(
                        EventBusMessage.EVENT_TYPE_SIM_STATE_CHANGE));

        // switch (strength) {
        // case 0:
        // ivSignalStrength.setBackgroundResource(R.drawable.strength_0);
        // break;
        // case 1:
        // ivSignalStrength.setBackgroundResource(R.drawable.strength_1);
        // break;
        // case 2:
        // ivSignalStrength.setBackgroundResource(R.drawable.strength_2);
        // break;
        // case 3:
        // ivSignalStrength.setBackgroundResource(R.drawable.strength_3);
        // break;
        // case 4:
        // ivSignalStrength.setBackgroundResource(R.drawable.strength_4);
        // break;
        // case 5:
        // ivSignalStrength.setBackgroundResource(R.drawable.strength_4);
        // break;
        // default:
        // ivSignalStrength.setBackgroundResource(R.drawable.strength_0);
        // break;
        //
        // }

        Log.i("test", " pre networkType=" + networkType);
        if (networkType == 0 && !wifiManager.isWifiEnabled()) {
            if (!phoneManager.isSimCardAccess()) {
                tvNetType.setText("");
            } else {
                noSigalCount++;
                if (noSigalCount < 20) {
                    networkType = preNetType;
                }

                if (!isCheck3G) {
                    Log.i("test", "无3G 信号 1分21秒后重启");

                    mHandler.postDelayed(switch3gStateTask, 33000);
                    isCheck3G = true;
                }
            }
        } else {
            if (networkType != 1) {// wifi状态不保存
                preNetType = networkType;
            }
            try {
                if (isCheck3G) {
                    mHandler.removeCallbacks(switch3gStateTask);
                    isCheck3G = false;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            noSigalCount = 0;

        }
        Log.i("test", "  networkType=" + networkType);
        switch (networkType) {
            case 0:
                tvNetType.setText("");
                break;
            case 1:
                tvNetType.setText("");
                iv_wifi.setVisibility(View.VISIBLE);
                break;
            case 2:
                tvNetType.setText("3G");
                iv_wifi.setVisibility(View.GONE);
                break;
            case 3:
                tvNetType.setText("E");
                iv_wifi.setVisibility(View.GONE);
                break;
            case 4:
                tvNetType.setText("4G");
                iv_wifi.setVisibility(View.GONE);
                break;
        }

        switch (operatorType) {
            case 0:
                tvOperationName.setText("");
                break;
            case 1:
                tvOperationName.setText(R.string.carrier_cmcc);
                break;
            case 2:
                tvOperationName.setText(R.string.carrier_unicom);
                break;
            case 3:
                tvOperationName.setText(R.string.carrier_telecom);
                break;
            case 4:
                tvOperationName.setText(R.string.carrier_other);
                break;
            default:
                break;
        }

    }

    class PhoneSignalStateListener extends PhoneStateListener {

        ServiceState mServiceState;
        SignalStrength mSignalStrength;

        @Override
        public void onSignalStrengthsChanged(SignalStrength signalStrength) {
            mSignalStrength = signalStrength;
//			updateSignalStrength(mSignalStrength);
            super.onSignalStrengthsChanged(signalStrength);
        }

        @Override
        public void onServiceStateChanged(ServiceState serviceState) {
            mServiceState = serviceState;

//			updateSignalStrength(mSignalStrength);
            if (!has_check_cheat_state) {
                sendCheatMessage();
                has_check_cheat_state = true;
            }
            // if (!MyPushMessageReceiver.hasBind) {
            // PushManager.startWork(getApplicationContext(),
            // PushConstants.LOGIN_TYPE_API_KEY,
            // "PmH9dMYDHDmA8nA5fVeP9XjS");
            // }

            super.onServiceStateChanged(serviceState);
        }
    }

    private void sendCheatMessage() {

        if (need2sendCheatMsg) {

            if (sp.getPickproofNumber().length() > 1 && sp.getPickproofState()) {
                Debug.printf("test",
                        "cheat 发送防盗短信 to" + sp.getPickproofNumber());
                SmsManager smsManager = SmsManager.getDefault();
                String sMsg = getResources().getString(R.string.guardsms);
                PendingIntent pi = PendingIntent.getBroadcast(
                        MainActivity.this, 0, new Intent(
                                ACTION_CHEAT_MESSAGE_RESULT), 0);
                smsManager.sendTextMessage(sp.getPickproofNumber(), null, sMsg,
                        pi, null);
                need2sendCheatMsg = false;
            }
        }
    }

    @Override
    protected void onDestroy() {

        this.stopService(new Intent(this, CXBMainService.class));

        this.stopService(new Intent(this, CameraDayNightService.class));
        navigationManager.stopNavigationListener();
        CxbEventBus.unResgist(CxbEventBus.EVENT_WEATHER_UPDATE, this);
        CxbEventBus.unResgist(CxbEventBus.EVENT_MESSAGE_CHANGE, this);
        CxbEventBus.unResgist(CxbEventBus.EVENT_GPS_CHANGE, this);
        EventBus.getDefault().unregister(this);
        this.unregisterReceiver(broadcastReceiver);
        Log.e(TAG, "ADDRESS: onDestory");

        wifiApManager.unregisterReceiver();
        if (Config.IS_MAP_IN_SDCARD) {
            this.unregisterReceiver(sdcardMountReceiver);
        }
        telephoneyManager.listen(phoneSignalStateListener,
                PhoneStateListener.LISTEN_NONE);
        // if (weatherManager != null) {
        // weatherManager.unregisterUpdateWeatherCallBack();
        // weatherManager = null;
        // }
        Debug.printf("onDestroy", szLog);
        Log.e("ares", "destroy");

        super.onDestroy();
    }

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {

            case MSG_TYPE_REFRESH_CAR_RECORDER_STATE:
                if (getCarRecorderState()) {// 行車記錄儀正在錄像
                    setRecording(true);
                } else {
                    setRecording(false);
                }

                break;
            case MSG_SHOW_COMPASS:
                compassView.setShowCompass(true);
                break;
            case MSG_MOVE_MAP_BACKGROUND:
                int mainTaskId = getMainPageTaskId();
                Debug.printf("test", "main taskId =" + mainTaskId);
                if (!isMapRuning) {
                    ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
                    activityManager.moveTaskToFront(mainTaskId, 0);
                }
                // screenCoverDialog.dimiss();

                compassView.setShowCompass(true);

                break;
        }

        return false;
    }

    @Override
    public int ttsStateChange(TtsState ttsState) {
        Debug.printf("TtsState:", "ttsState=" + ttsState);
        if (ttsState == TtsState.START) {
            Log.e("ares", "start");
            Intent i = new Intent();
            i.setAction(Constants.CXBBroadcast.TTS_START_ACTION);
            sendBroadcast(i);

        } else {
            Log.e("ares", "stop");
            Intent i = new Intent();
            i.setAction(Constants.CXBBroadcast.TTS_STOP_ACTION);
            sendBroadcast(i);
        }
        return 0;
    }

    private void startMapViewActivity() {
        if (!CommonUtils.isInnerMemoryExists(context)) {

            if (tts != null) {
                tts.speak(getString(R.string.init_map));
            }
            Toast.makeText(this, R.string.init_map, Toast.LENGTH_LONG).show();
            return;
        }
        Intent intent1 = new Intent();
        intent1.setAction(Intent.ACTION_MAIN);
        intent1.addCategory(Intent.CATEGORY_LAUNCHER);

        intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);

        if (Config.getMapDefault(this) == Config.MAP_GOOGLE_MAP) {
            intent1.setClassName(Config.GOOGLE_MAP_PACKAGE_NAME, Config.GOOGLE_MAP_MAIN_ACTIVITY);
            intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                    | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
            Log.e(TAG, "START GOOGLE MAP");

        } else if (Config.getMapDefault(this) == Config.MAP_AUTOMAP_CAR) {

            intent1.setPackage("com.autonavi.amapauto");
            intent1.setClassName("com.autonavi.amapauto",
                    "com.autonavi.auto.remote.fill.UsbFillActivity");
            intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                    | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);

        } else if (Config.getMapDefault(this) == Config.MAP_AUTOMAP_LITE) {

            intent1.setPackage("com.autonavi.amapautolite");
            intent1.setClassName("com.autonavi.amapautolite",
                    "com.autonavi.auto.remote.fill.UsbFillActivity");
            intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                    | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);

        } else if (Config.getMapDefault(this) == Config.MAP_AUTOMAP) {
            intent1.setClassName("com.autonavi.minimap",
                    "com.autonavi.map.activity.SplashActivity");
        } else if (Config.getMapDefault(this) == Config.MAP_BAIDU) {
            // Intent.FLAG_ACTIVITY_NEW_TASK);
            Uri uri = Uri.parse("bdnavi://launch?src=com.cxb");
            intent1 = new Intent("com.baidu.navi.action.START", uri);
            intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        } else if (Config.getMapDefault(this) == Config.MAP_AUTONAVI) {
            intent1.setClassName("com.autonavi.xmgd.navigator",
                    "com.autonavi.xmgd.navigator.Warn");
        }

        startActivity(intent1);
    }

    private void openApp(String packageName) {
        if (packageName == null) {
            return;
        }
        PackageManager pm = this.getPackageManager();
        PackageInfo pi = null;
        try {
            pi = pm.getPackageInfo(packageName, 0);
        } catch (NameNotFoundException e) {

            e.printStackTrace();
            return;
        }

        Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
        resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        resolveIntent.setPackage(pi.packageName);

        List<ResolveInfo> apps = pm.queryIntentActivities(resolveIntent, 0);

        if (apps.size() < 1) {
            return;
        }
        ResolveInfo ri = apps.get(0);
        if (ri != null) {
            // String packageName = ri.activityInfo.packageName;
            String className = ri.activityInfo.name;

            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);

            ComponentName cn = new ComponentName(packageName, className);

            intent.setComponent(cn);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            this.startActivity(intent);

            // // 隐藏launcherView
            // if (launcherView != null)
            // launcherView.dismiss();
        }
    }

    private GpsDestinationInfo decodeIPMSG(Bundle bundle) {
        GpsDestinationInfo gpsInfo = null;

        if (bundle == null) {
            return null;
        }

        gpsInfo = new GpsDestinationInfo();
        gpsInfo.destName = bundle.getString("poidesc");
        gpsInfo.longitude = bundle.getDouble("longitude");
        gpsInfo.latitude = bundle.getDouble("latitude");

        Log.e("ares", "destName=" + gpsInfo.destName + " longitude="
                + gpsInfo.longitude + " latitude=" + gpsInfo.latitude);

        return gpsInfo;
    }

    public void onEventMainThread(EventBusMessage eventBusMessage) {
        if (eventBusMessage.getEventType() == EventBusMessage.EVENT_TYPE_WEIXIN_BIND_STATE_CHANGE) {
            // 微信状态改变微信
            BindStatus bindStatus = (BindStatus) eventBusMessage.getArg();
            if (bindStatus.bindStatus) {
                Tts.showToast(
                        this,
                        getString(R.string.has_bind_weixin_tts,
                                bindStatus.weixin.nickName), 0);
            } else {
                Tts.showToast(this, getString(R.string.has_unbind_weixin_tts),
                        0);
            }
        } else if (eventBusMessage.getEventType() == EventBusMessage.EVENT_TYPE_OTA_UPDATE) {
            ivSetting.setVisibility(View.VISIBLE);
            update_find = true;
        } else if (eventBusMessage.getEventType() == EventBusMessage.EVENT_PHONE_SIGAL_CHANGE) {
            PhoneSigal phoneSigal = (PhoneSigal) eventBusMessage.getArg();
            updateSignalStrength(phoneSigal.getLevel());

            Log.i(TAG, "updateTelephoneSingal level=" + phoneSigal.getLevel());
        }

    }

    public void onEventMainThread(SMS sms) {
        tts.speak(getString(R.string.receive_a_new_sms));
        ivMsg.setVisibility(View.VISIBLE);

    }

    private void setGprsEnabled(boolean isEnable) {
        ConnectivityManager mCM = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        Class cmClass = mCM.getClass();
        Class[] argClasses = new Class[1];
        argClasses[0] = boolean.class;

        try {
            Method method = cmClass.getMethod("setMobileDataEnabled",
                    argClasses);
            method.invoke(mCM, isEnable);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

    }

    public void updateWifiAPApState() {
        if (wifiAPUtil.getWifiApState(wifiManager) == WifiAPUtil.WIFI_AP_STATE_ENABLED) {
            iv_wifi_ap.setVisibility(View.VISIBLE);
            iv_wifi_ap_status.setImageResource(R.drawable.wifi_ap_open);

        } else {
            iv_wifi_ap.setVisibility(View.GONE);
            iv_wifi_ap_status.setImageResource(R.drawable.wifi_ap_close);
        }
        if (wifiAPUtil.getWifiApState(wifiManager) == WifiAPUtil.WIFI_AP_STATE_ENABLED) {
            iv_wifi_ap.setVisibility(View.VISIBLE);

        } else {
            iv_wifi_ap.setVisibility(View.GONE);

        }
    }

    public void updateWifiState() {

        ConnectivityManager netWorkManager = (ConnectivityManager) context
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo.State state = netWorkManager.getNetworkInfo(
                ConnectivityManager.TYPE_WIFI).getState();
        if (state == NetworkInfo.State.CONNECTED) {
            iv_wifi.setVisibility(View.VISIBLE);
            tvNetType.setText("");
            // if (!MyPushMessageReceiver.hasBind) {
            // PushManager.startWork(getApplicationContext(),
            // PushConstants.LOGIN_TYPE_API_KEY,
            // "PmH9dMYDHDmA8nA5fVeP9XjS");
            // }

        } else {
            iv_wifi.setVisibility(View.GONE);
        }

        if (wifiManager.isWifiEnabled()) {

            iv_wifi_status.setImageResource(R.drawable.wifi_icon_open);
            // tvNetType.setText("");
            // iv_wifi.setVisibility(View.VISIBLE);
        } else {
            iv_wifi_status.setImageResource(R.drawable.wifi_close);
        }
    }

    private boolean getCarRecorderState() {
        try {
            Uri uri = Uri
                    .parse("content://provider.cxb.car_recorder/car_recorder_state");
            Cursor cursor = getContentResolver().query(uri, null, null, null,
                    null);
            boolean state = false;
            if (cursor == null) {
                return false;
            }
            if (cursor.moveToNext()) {
                state = cursor.getInt(cursor.getColumnIndex("state")) == 1;
            }
            cursor.close();

            return state;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;

    }

    @Override
    public void onWifiApStateChanged(int state) {
        sp.setWifiApEnable(state == 1);
        updateWifiAPApState();
        if (state == WifiAPUtil.WIFI_AP_STATE_DISABLED) {
            TTSToast.show(this, getString(R.string.wifiap_close), 0);

        } else if (state == WifiAPUtil.WIFI_AP_STATE_ENABLED) {
            TTSToast.show(this, getString(R.string.wifiap_open), 0);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == Constants.HareWareKeyCode.KEYCODE_HOME) {
            Intent iRecorder = new Intent();
            iRecorder.setAction("preview_window_off");
            context.sendBroadcast(iRecorder);
        } else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN
                || keyCode == KeyEvent.KEYCODE_VOLUME_UP) {

            updateVolumnButton();

        }
        return super.onKeyDown(keyCode, event);
    }

    public void setUpMapBackGround() {

        if (firstSettingMap && sp.getIsSetupWizard()) {
            startMapViewActivity();
            mHandler.postDelayed(new Runnable() {

                @Override
                public void run() {
                    tts.speak(getString(R.string.setting_up_map));

                }
            }, 3000);
            new Thread(new MapMonitorTask()).start();
            firstSettingMap = false;
            setUp_map = false;
        } else {
            mHandler.sendEmptyMessage(MSG_SHOW_COMPASS);
        }

    }

    // MSG_MOVE_MAP_BACKGROUND
    int checkGaodeLogoPageCount = 0;

    class MapMonitorTask implements Runnable {
        @Override
        public void run() {
            while (true) {

                boolean isAtMap = isAtMapPage();

                if (isAtMap) {
                    ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
                    String runningActivity = activityManager.getRunningTasks(1)
                            .get(0).topActivity.getClassName();

                    if (runningActivity.endsWith("Logo")) {
                        try {

                            checkGaodeLogoPageCount++;
                            if (checkGaodeLogoPageCount < 20) {
                                Thread.sleep(5000);
                                continue;
                            }
                        } catch (InterruptedException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }
                    }

                    try {
                        mHandler.sendEmptyMessage(MSG_SHOW_COMPASS);
                        Thread.sleep(10000);
                    } catch (InterruptedException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    mHandler.sendEmptyMessage(MSG_MOVE_MAP_BACKGROUND);
                    break;
                } else {
                    mHandler.sendEmptyMessage(MSG_SHOW_COMPASS);
                    break;

                }

            }

        }
    }

    public boolean isAtMapPage() {

        ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        String runningActivity = activityManager.getRunningTasks(1).get(0).topActivity
                .getPackageName();
        return runningActivity.equals("com.autonavi.xmgd.navigator");

    }

    public int getMainPageTaskId() {
        final ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningTaskInfo> runingAppList = activityManager
                .getRunningTasks(10);
        for (RunningTaskInfo runningTaskInfo : runingAppList) {
            if (runningTaskInfo.baseActivity.getPackageName().equals("com.cxb")) {
                return runningTaskInfo.id;
            }
        }

        return -1;
    }

    public void onEventMainThread(Integer angle) {
        Log.i("test", "angle=" + angle);
        compassView.rotateCompass(angle);
    }

    private final BroadcastReceiver sdcardMountReceiver = new BroadcastReceiver()

    {
        public void onReceive(Context context, Intent intent) {

            Log.i("test", "sdcard " + intent.getAction());
            Log.i("test",
                    "sdcard state " + Environment.getExternalStorageState());
            Log.i("test",
                    "sdcard state" + Environment.getExternalStorageDirectory());
            if (intent.getAction()
                    .equals("android.intent.action.MEDIA_MOUNTED")) {// SD

                // 卡已经成功挂载
                // imagepath =
                //
                // android.os.Environment.getExternalStorageDirectory();//
                // 你的SD卡路径
                Log.i("test", "==MEDIA_MOUNTED");
                if (setUp_map) {
                    Debug.printf("test", "task setUpMapBackGround");

                    mHandler.postDelayed(new Runnable() {

                        @Override
                        public void run() {
                            // TODO Auto-generated method stub
                            if (!CommonUtils.isSDExists(MainActivity.this)) {
                                mHandler.postDelayed(this, 3000);
                                return;
                            }
                            compassView.setShowCompass(false);
                            doSetUpMap();
                        }
                    }, 3000);
                }
                // mHandler.postDelayed(new Runnable() {
                //
                // @Override
                // public void run() {
                // }
                // }, 3000);

            }

            if (intent.getAction()
                    .equals("android.intent.action.MEDIA_REMOVED")// 各种未挂载状态
                    || intent.getAction().equals(
                    "android.intent.action.ACTION_MEDIA_UNMOUNTED")
                    || intent.getAction().equals(
                    "android.intent.action.ACTION_MEDIA_BAD_REMOVAL")) {

                // imagepath = android.os.Environment.getDataDirectory();//
                // 你的本地路径

            }

        }

    };

    private void doSetUpMap() {
        ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        final ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
        if (NavigationManager.gpsDestinationInfoNeed2Navi != null) {
            navigationManager
                    .startupNavigation(NavigationManager.gpsDestinationInfoNeed2Navi);
            NavigationManager.gpsDestinationInfoNeed2Navi = null;
            compassView.setShowCompass(true);
        } else {
            if (sp.getSetUpEdogWhenBootUp()) {
                if (!cn.getPackageName().equals("com.autonavi.xmgd.navigator")) {
                    setUpMapBackGround();
                }
            }
        }
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 1) {
            switch (resultCode) {
                case TextToSpeech.Engine.CHECK_VOICE_DATA_PASS: // 这个返回结果表明TTS
                    // Engine可以用

                    tts = new Tts(getApplicationContext());
                    tts.registerTtsStateChange(this);

                    mHandler.postDelayed(new Runnable() {

                        @Override
                        public void run() {
                            if (firstBootComplete) {
                                // if (CommonUtils.getVersionType() ==
                                // CommonUtils.VERSION_AMI35C) {
                                // tts.speak(getString(R.string.welcome_ami));
                                // } else if (CommonUtils.getVersionType() ==
                                // CommonUtils.VERSION_ZHAOSHAN) {
                                // tts.speak(getString(R.string.welcome_zhanshan));
                                // }
                                // tts.speak(getString(ClientManager.getWelcomeR()));
                                // sendCheatMessage();
                                firstBootComplete = false;
                            }
                            if (sp.getSetUpEdogWhenBootUp()
                                    && setUp_map
                                    && (CommonUtils.isSDExists(MainActivity.this) || !Config.IS_MAP_IN_SDCARD)
                                    && !CommonUtils.isUSBMass()) {

                                mHandler.postDelayed(new Runnable() {

                                    @Override
                                    public void run() {
                                        Debug.printf("test",
                                                "task setUpMapBackGround");
                                        if (Environment.MEDIA_MOUNTED
                                                .equals(Environment
                                                        .getExternalStorageState())) {
                                            compassView.setShowCompass(false);
                                            doSetUpMap();
                                        } else {
                                            mHandler.postDelayed(this, 2000);
                                        }
                                    }
                                }, 12000);
                            }
                        }
                    }, 5000);
                    break;
                case TextToSpeech.Engine.CHECK_VOICE_DATA_BAD_DATA: // 需要的语音数据已损坏
                case TextToSpeech.Engine.CHECK_VOICE_DATA_MISSING_DATA: // 缺少需要语言的语音数据
                case TextToSpeech.Engine.CHECK_VOICE_DATA_MISSING_VOLUME: // 缺少需要语言的发音数据
                    // 这三种情况都表明数据有错,重新下载安装需要的数据
                    // Log.v(TAG, "Need language stuff:" + resultCode);
                    Intent dataIntent = new Intent();
                    dataIntent
                            .setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
                    startActivity(dataIntent);

                    break;
                case TextToSpeech.Engine.CHECK_VOICE_DATA_FAIL: // 检查失败
                default:
                    // Log.v(TAG, "Got a failure. TTS apparently not available");
                    break;

            }
        }//added by jerry for voice navigation
        else if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode == Activity.RESULT_OK) {
            //取得语音的字符
            ArrayList<String> results = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
            String resultsString = "";
            if (results != null) {
                resultsString = results.get(0);
            }
            Toast.makeText(MainActivity.this, resultsString, Toast.LENGTH_LONG).show();
            if (!TextUtils.isEmpty(resultsString)) {
                //选择地址
                initAddressDialog();
                GoogleWebServiceUtil.queryAutoComplete(resultsString, mQueryAddressCallball);
            }

        }
    }

    private void setPhoneMute(boolean enable) {

        if (enable) {
            int volumn = audioManager
                    .getStreamVolume(AudioManager.STREAM_MUSIC);
            audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 0, 0);
            audioManager
                    .setStreamVolume(AudioManager.STREAM_NOTIFICATION, 0, 0);
            audioManager.setStreamVolume(AudioManager.STREAM_SYSTEM, 0, 0);
            audioManager.setStreamVolume(AudioManager.STREAM_RING, 0, 0);
            audioManager.setStreamVolume(AudioManager.STREAM_ALARM, 0, 0);
            audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
            sp.setVoulmn(volumn);

        } else {
            int volumn = sp.getVolumn();
            audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, volumn, 0);
            audioManager.setStreamVolume(AudioManager.STREAM_NOTIFICATION,
                    volumn, 0);
            audioManager.setStreamVolume(AudioManager.STREAM_ALARM, volumn, 0);
            audioManager.setStreamVolume(AudioManager.STREAM_SYSTEM, volumn, 0);
            audioManager.setStreamVolume(AudioManager.STREAM_RING, volumn, 0);
            audioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
        }
    }

    private void updateVolumnButton() {
        ivAudio.setBackgroundResource(R.drawable.btn_main_voice);

//        if (isMute()) {
//            // ivAudio.setImageResource(R.drawable.mute);
//            ivAudio.setBackgroundResource(R.drawable.btn_mic);
//        } else {
//            ivAudio.setBackgroundResource(R.drawable.btn_mic_pressed);
            // ivAudio.setImageResource(R.drawable.volumn);
//			int volumn = audioManager
//					.getStreamVolume(AudioManager.STREAM_MUSIC);
//			int maxVolumn = audioManager
//					.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
//			int[] volumnImageArray = { R.drawable.ic_volumn1,
//					R.drawable.ic_volumn2, R.drawable.ic_volumn3,
//					R.drawable.volumn4 };
//			float step = maxVolumn / 3.0f;
//			int index = (int) (volumn / step);
//			if (index >= 2) {
//				index = 2;
//			}
//			sp.setVoulmn(volumn);
//			Log.i("test", "maxVolumn=" + maxVolumn + " step=" + step
//					+ " volumn=" + volumn);
//			ivAudio.setBackgroundResource(volumnImageArray[index]);
//        }

    }

    private boolean isMute() {
        int volumn = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);

        Log.i("test", " volumn=" + volumn);
        return volumn <= 0;
    }

    /**
     * 2015-06-08 查找Service是否在启动中
     **/
    private boolean isProcessRunning(Context mContext, String packageName) {
        boolean isRunning = false;
        ActivityManager activityManager = (ActivityManager) mContext
                .getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningAppProcessInfo> appProcessList = activityManager
                .getRunningAppProcesses();
        if (!(appProcessList.size() > 0)) {
            return false;
        }
        for (int i = 0; i < appProcessList.size(); i++) {
            if (appProcessList.get(i).processName.equals(packageName) == true) {
                isRunning = true;
                break;
            }
        }
        return isRunning;
    }

    private boolean checkAutoNaviPackageExisted(boolean flagFast, String pkgName) {
        boolean isProcessRunning = false;
        isProcessRunning = isProcessRunning(this, pkgName);

        if (btn_closeAutoNavi != null && !flagFast) {
            if (isProcessRunning) {
                btn_closeAutoNavi.setVisibility(View.VISIBLE);
            } else {
                btn_closeAutoNavi.setVisibility(View.GONE);
            }
        }
        return isProcessRunning;
    }

    private void closeProcess(String packageName) {
        ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        try {
            Method forceStopPackage = am.getClass().getDeclaredMethod(
                    "forceStopPackage", String.class);
            forceStopPackage.setAccessible(true);
            forceStopPackage.invoke(am, packageName);
        } catch (SecurityException e) {

        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        // int pid;
        // List<RunningAppProcessInfo> appProcessList =
        // am.getRunningAppProcesses();
        // if (!(appProcessList.size() > 0)) {
        // return ;
        // }
        // for (int i = 0; i < appProcessList.size(); i++) {
        // if (appProcessList.get(i).processName.equals(packageName) == true) {
        // pid = appProcessList.get(i).pid;
        // RootContext rootContext = RootContext.getInstance(this);
        // rootContext.runCommand("kill "+pid);
        // break;
        // }
        // }
    }

    class Switch3GStateTask implements Runnable {
        @Override
        public void run() {
            if (!CommonUtils.isNetworkAvailable(context)
                    && phoneManager.isSimCardAccess()) {
                Log.i("test", "重启 3G信号");
                CommonUtils.switch3GMode(MainActivity.this);

                mHandler.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        isCheck3G = false;

                    }
                }, 3000);
            }

        }
    }

    /**
     * @param
     * @return void
     * @throws
     * @Description:启动翼卡app
     * @author 陈伟斌 2016-1-12
     */
    public void setupECardApp() {

        Intent intent = new Intent();
        intent.setComponent(new ComponentName("com.coagent.ecar",
                "com.coagent.ecarnet.car.service.BootService"));

        startService(intent);

    }


    //============================================== added by jerry =========================================================================
    //============================================== added by jerry =========================================================================
    //============================================== added by jerry =========================================================================
    //============================================== added by jerry =========================================================================
    //============================================== added by jerry =========================================================================
    //============================================== added by jerry =========================================================================
    //============================================== added by jerry =========================================================================
    //============================================== added by jerry =========================================================================
    public static final int VOICE_RECOGNITION_REQUEST_CODE = 100;

    //	public static final int VOICE_RECOGNITION_REQUEST_CODE2 = 102;
    private void startVoiceRecognize() {
        try {
            //用Intent来传递语音识别的模式,并且开启语音模式
            Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
            //语言模式和自由形式的语音识别
            intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
            //提示语言开始
            intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "please Speak!");
            //开始语音识别
            startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
        } catch (ActivityNotFoundException e) {
            Toast.makeText(MainActivity.this, "找不到语音设备", Toast.LENGTH_LONG).show();
        }

    }

    private void startMap() {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        ComponentName cn = new ComponentName("broderactivity.example.com.mybroderact", "broderactivity.example.com.mybroderact.MainActivity");
        intent.setComponent(cn);
        startActivity(intent);

    }


    private org.xutils.common.Callback.CommonCallback<String> mQueryAddressCallball = new org.xutils.common.Callback.CommonCallback<String>() {
        @Override
        public void onSuccess(String result) {
            Log.e(TAG, "onSuccess");
            List<String> address = GoogleWebServiceUtil.parseJsonForAddress(result);
            if (address == null) {
                TTSToast.show(MainActivity.this, getString(R.string.address_not_found), Toast.LENGTH_LONG);
                return;
            }
            Log.e(TAG, address.toString() + " thread:" + Thread.currentThread().getName());
            ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, address);
            mAddressListView.setAdapter(adapter);
            mAddressDialog.show();
        }

        @Override
        public void onError(Throwable ex, boolean isOnCallback) {
            Log.e(TAG, "onError");
            ex.printStackTrace();
            TTSToast.show(MainActivity.this, "连接出错", Toast.LENGTH_LONG);

        }

        @Override
        public void onCancelled(CancelledException cex) {
            cex.printStackTrace();
            TTSToast.show(MainActivity.this, "取消", Toast.LENGTH_LONG);
        }

        @Override
        public void onFinished() {
            TTSToast.show(MainActivity.this, "结束", Toast.LENGTH_LONG);
        }
    };

    private org.xutils.common.Callback.CommonCallback<String> mQueryLocationPointCallball = new org.xutils.common.Callback.CommonCallback<String>() {
        @Override
        public void onSuccess(String result) {
            Log.e(TAG, result);
            LocationPoint locationPoint = GoogleWebServiceUtil.parseJsonForLatAndLng(result);
            GpsDestinationInfo destinationInfo = new GpsDestinationInfo();
            destinationInfo.destName = mCurrentAddress;
            destinationInfo.latitude = locationPoint.latitude;
            destinationInfo.longitude = locationPoint.longitude;
            navigationManager.startupNavigation(destinationInfo);
        }

        @Override
        public void onError(Throwable ex, boolean isOnCallback) {
            ex.printStackTrace();
            TTSToast.show(MainActivity.this, "连接出错", Toast.LENGTH_LONG);
        }

        @Override
        public void onCancelled(CancelledException cex) {
        }

        @Override
        public void onFinished() {

        }
    };

    private Dialog mAddressDialog;
    private ListView mAddressListView;
    private String mCurrentAddress;
    private AdapterView.OnItemClickListener mOnAddressClick = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
            mAddressDialog.dismiss();
            mCurrentAddress = ((TextView) view).getText().toString();
            GoogleWebServiceUtil.searchLocationPointByAddress(mCurrentAddress, mQueryLocationPointCallball);
        }
    };

    private void initAddressDialog() {
        //初始化mAddressDialog
        if (mAddressDialog == null) {
            mAddressDialog = new Dialog(this, R.style.commonDialog);
            mAddressDialog.getWindow().setContentView(R.layout.address_list);
            mAddressDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
            mAddressDialog.setCancelable(false);
            mAddressDialog.setCanceledOnTouchOutside(true);

            mAddressListView = (ListView) mAddressDialog.getWindow().findViewById(R.id.address_listview);
            mAddressListView.setOnItemClickListener(mOnAddressClick);
        }

    }

    //add end
    //================================================================================================================================
    //================================================================================================================================
    //================================================================================================================================
    //================================================================================================================================
}
